package com.holic.spring.aigc.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.holic.spring.aigc.model.spark.SparkRequest;
import com.holic.spring.aigc.model.spark.SparkResponse;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName SparkClient
 * @Description
 * @Author Neil
 * @Date 2024/11/20 9:24
 * @Version V1.0
 **/
@Service
public class SparkClient {

    private RestTemplate restTemplate = new RestTemplate();

    public SparkResponse request(SparkRequest request) {
        String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer YscOVKMDnxUppqZcxbSd:sVeRckKBAhVDKdbJABkW");
        // 创建请求体
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonRequest = objectMapper.writeValueAsString(request);
            HttpEntity<String> entity = new HttpEntity<>(jsonRequest, headers);
            // 发送 POST 请求
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            // 处理响应
            if (response.getStatusCode().is2xxSuccessful()) {
                return objectMapper.readValue(response.getBody(), SparkResponse.class);
            } else {
                throw new RuntimeException("Failed : HTTP error code : " + response.getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to send POST request", e);
        }
    }

}
